/*
 * LianHaidong <lianhaidong@gmail.com>
 */

#include <stdio.h>
#include <ctype.h>
#include "utils/str_utils.h"
#include "utils/debug.h"

#define is_pure_space(c)  ((c) == ' ' || (c) == '\t')

#define is_char(c) (isalpha((c)) || (c) == '/' 	\
		|| isdigit((c)) || (c) == '.' 	\
		|| (c) == '_' || (c) == ':'	\
		|| (c) == '@')

enum GetWordCode get_word(char **p, char *word, int max_len)
{

start:
	if ((**p) == '\0') {
		return GET_WORD_OVER;
	}
	if (is_pure_space(**p)) {
		(*p) ++;
		goto start;
	}

	if ((**p) == '\r') {
		(*p) ++;
		goto s2;
	}
	if (is_char(**p)) {
		goto s1;
	}
	
	return -1;

s1:
	if (is_char(**p)) {
		*word++ = *(*p) ++;
		goto s1;
	}

	if (is_pure_space(**p)) {
		*word++ = '\0';
		return GET_WORD_MORE;
	}

	if ((**p) == '\r') {
		*word++ = '\0';
		(*p) ++;
		goto s2;
	}
	if (**p == '\0') {
		return -1;
	}
	return -1;
s2:
	if (**p != '\n') {
		return -1;
	}
	(*p) ++;
	if (**p == '\r') {
		(*p) ++;
		goto s3;
	} else if (is_char(**p)) {
		return GET_WORD_MORE;
	}
	return -1;
s3:
	if (**p != '\n') {
		return -1;
	}

	return GET_WORD_OVER;
}

int strstart(const char *start, const char *str)
{
	while (*start && *str && *start++ == *str ++)  ;

	return !*start;
}

int strstartp(const char *start, const char **str)
{
	while (*start && **str && *start++ == *(*str) ++)  ;

	return !*start;
}



#ifdef GET_WORD_STUB
int main()
{
	char *in_buf = "CBS/1.0 USER_REG\r\n"
		"seq:0\r\n"
		"uuid:123456789\r\n"
		"email:lianhd@126.com\r\n"
		"passwd:1234456\r\n\r\n";
	char word[128];
	char *p = in_buf;
	int rv;

	do {
		rv =get_word(&p, word, sizeof(word));
		msg("word = %s", word);
	} while (rv == GET_WORD_MORE);

	return 0;
}

#endif	/* GET_WORD_STUB */

